package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.pojo.entity.Grade;
import com.demo.pojo.entity.Teacher;
import com.demo.service.TeacherUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 教师用户控制器
 */
@RestController
@RequestMapping("/teacher-user")
@CrossOrigin
public class TeacherUserController {
    
    @Autowired
    private TeacherUserService teacherUserService;
    
    /**
     * 教师登录
     */
    @PostMapping("/login")
    public Result<Teacher> teacherLogin(@RequestParam String teNo, @RequestParam String password) {
        try {
            Teacher teacher = teacherUserService.teacherLogin(teNo, password);
            if (teacher != null) {
                return Result.success(teacher);
            } else {
                return Result.error("登录失败，工号或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师个人信息
     */
    @GetMapping("/info/{teacherId}")
    public Result<Teacher> getTeacherInfo(@PathVariable Long teacherId) {
        try {
            Teacher teacher = teacherUserService.getTeacherInfo(teacherId);
            return Result.success(teacher);
        } catch (Exception e) {
            return Result.error("获取教师信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新教师个人信息
     */
    @PutMapping("/update")
    public Result<String> updateTeacherInfo(@RequestBody Teacher teacher) {
        try {
            boolean success = teacherUserService.updateTeacherInfo(teacher);
            if (success) {
                return Result.success("更新教师信息成功");
            } else {
                return Result.error("更新教师信息失败");
            }
        } catch (Exception e) {
            return Result.error("更新教师信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师课表
     */
    @GetMapping("/schedule/{teacherId}/{semester}")
    public Result<List<ScheduleListDTO>> getTeacherSchedule(@PathVariable Long teacherId, 
                                                          @PathVariable String semester) {
        try {
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherSchedule(teacherId, semester);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师课表失败：" + e.getMessage());
        }
    }

    /**
     * 获取教师课表（学期可选，后端做兜底：advanced -> 2025-1）
     */
    @GetMapping("/schedule/{teacherId}")
    public Result<List<ScheduleListDTO>> getTeacherScheduleFallback(
            @PathVariable Long teacherId,
            @RequestParam(value = "semester", required = false) String semester) {
        try {
            String resolved = semester; 
            if (resolved == null || resolved.isBlank()) {
                resolved = "advanced";
            }
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherSchedule(teacherId, resolved);
            if ((schedules == null || schedules.isEmpty()) && !"2025-1".equals(resolved)) {
                // 兜底尝试另一个常用学期
                schedules = teacherUserService.getTeacherSchedule(teacherId, "2025-1");
            }
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师本周课表
     */
    @GetMapping("/schedule/week/{teacherId}/{semester}/{weekNo}")
    public Result<List<ScheduleListDTO>> getTeacherWeekSchedule(@PathVariable Long teacherId, 
                                                              @PathVariable String semester, 
                                                              @PathVariable Integer weekNo) {
        try {
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherWeekSchedule(teacherId, semester, weekNo);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师本周课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师今日课表
     */
    @GetMapping("/schedule/today/{teacherId}/{semester}/{weekNo}/{dayOfWeek}")
    public Result<List<ScheduleListDTO>> getTeacherTodaySchedule(@PathVariable Long teacherId, 
                                                               @PathVariable String semester, 
                                                               @PathVariable Integer weekNo, 
                                                               @PathVariable Integer dayOfWeek) {
        try {
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherTodaySchedule(teacherId, semester, weekNo, dayOfWeek);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师今日课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 申请调课
     */
    @PostMapping("/schedule/change")
    public Result<String> applyScheduleChange(@RequestParam Long scheduleId, 
                                            @RequestParam String reason, 
                                            @RequestParam Long newTimeSlotId, 
                                            @RequestParam Long newClassroomId) {
        try {
            boolean success = teacherUserService.applyScheduleChange(scheduleId, reason, newTimeSlotId, newClassroomId);
            if (success) {
                return Result.success("调课申请提交成功");
            } else {
                return Result.error("调课申请提交失败");
            }
        } catch (Exception e) {
            return Result.error("调课申请提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师工作量统计
     */
    @GetMapping("/workload/{teacherId}/{semester}")
    public Result<Map<String, Object>> getTeacherWorkloadStats(@PathVariable Long teacherId, 
                                                              @PathVariable String semester) {
        try {
            Map<String, Object> stats = teacherUserService.getTeacherWorkloadStats(teacherId, semester);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取教师工作量统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师时间偏好
     */
    @GetMapping("/preference/{teacherId}")
    public Result<Map<String, Object>> getTeacherTimePreference(@PathVariable Long teacherId) {
        try {
            Map<String, Object> preferences = teacherUserService.getTeacherTimePreference(teacherId);
            return Result.success(preferences);
        } catch (Exception e) {
            return Result.error("获取教师时间偏好失败：" + e.getMessage());
        }
    }
    
    /**
     * 设置教师时间偏好
     */
    @PostMapping("/preference/{teacherId}")
    public Result<String> setTeacherTimePreference(@PathVariable Long teacherId, 
                                                 @RequestBody Map<String, Object> preferences) {
        try {
            boolean success = teacherUserService.setTeacherTimePreference(teacherId, preferences);
            if (success) {
                return Result.success("设置教师时间偏好成功");
            } else {
                return Result.error("设置教师时间偏好失败");
            }
        } catch (Exception e) {
            return Result.error("设置教师时间偏好失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师的学生列表
     */
    @GetMapping("/students/{teacherId}/{semester}")
    public Result<List<Map<String, Object>>> getTeacherStudents(@PathVariable Long teacherId,
                                                                @PathVariable String semester) {
        try {
            System.out.println("===== 获取教师学生列表 =====");
            System.out.println("教师ID: " + teacherId);
            System.out.println("学期: " + semester);
            
            List<Map<String, Object>> students = teacherUserService.getTeacherStudents(teacherId, semester);
            
            System.out.println("查询到学生数量: " + (students != null ? students.size() : 0));
            
            return Result.success(students);
        } catch (Exception e) {
            System.err.println("获取学生列表失败，详细错误：");
            e.printStackTrace();
            return Result.error("获取学生列表失败：" + e.getMessage());
        }
    }
    
    // ==================== 成绩管理相关接口 ====================
    
    /**
     * 获取教师的成绩列表
     */
    @GetMapping("/grades/{teacherId}")
    public Result<List<Map<String, Object>>> getTeacherGrades(
            @PathVariable Long teacherId,
            @RequestParam(required = false) String semester,
            @RequestParam(required = false) Long courseId,
            @RequestParam(required = false) Long clazzId,
            @RequestParam(required = false) String studentName,
            @RequestParam(required = false) Integer status) {
        try {
            List<Map<String, Object>> grades = teacherUserService.getTeacherGrades(
                teacherId, semester, courseId, clazzId, studentName, status);
            return Result.success(grades);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取成绩列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师的课程列表
     */
    @GetMapping("/courses/{teacherId}")
    public Result<List<Map<String, Object>>> getTeacherCourses(
            @PathVariable Long teacherId,
            @RequestParam(required = false) String semester) {
        try {
            List<Map<String, Object>> courses = teacherUserService.getTeacherCourses(teacherId, semester);
            return Result.success(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取课程的班级列表
     */
    @GetMapping("/course/{courseId}/classes")
    public Result<List<Map<String, Object>>> getCourseClasses(
            @PathVariable Long courseId,
            @RequestParam Long teacherId,
            @RequestParam(required = false) String semester) {
        try {
            List<Map<String, Object>> classes = teacherUserService.getCourseClasses(teacherId, courseId, semester);
            return Result.success(classes);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取班级列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取班级的学生列表
     */
    @GetMapping("/class/{clazzId}/students")
    public Result<List<Map<String, Object>>> getClassStudents(
            @PathVariable Long clazzId,
            @RequestParam(required = false) Long courseId) {
        try {
            List<Map<String, Object>> students = teacherUserService.getClassStudents(clazzId, courseId);
            return Result.success(students);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取学生列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加成绩
     */
    @PostMapping("/grade/add")
    public Result<String> addGrade(@RequestBody Grade grade) {
        try {
            boolean success = teacherUserService.addGrade(grade);
            if (success) {
                return Result.success("添加成绩成功");
            } else {
                return Result.error("添加成绩失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新成绩
     */
    @PutMapping("/grade/update")
    public Result<String> updateGrade(@RequestBody Grade grade) {
        try {
            boolean success = teacherUserService.updateGrade(grade);
            if (success) {
                return Result.success("更新成绩成功");
            } else {
                return Result.error("更新成绩失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除成绩
     */
    @DeleteMapping("/grade/delete/{gradeId}")
    public Result<String> deleteGrade(@PathVariable Long gradeId) {
        try {
            boolean success = teacherUserService.deleteGrade(gradeId);
            if (success) {
                return Result.success("删除成绩成功");
            } else {
                return Result.error("删除成绩失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除成绩失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量添加成绩
     */
    @PostMapping("/grade/batch-add")
    public Result<String> batchAddGrades(@RequestBody List<Grade> grades) {
        try {
            boolean success = teacherUserService.batchAddGrades(grades);
            if (success) {
                return Result.success("批量添加成绩成功");
            } else {
                return Result.error("批量添加成绩失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量添加成绩失败：" + e.getMessage());
        }
    }
    
    // ==================== 选课审核相关接口 ====================
    
    /**
     * 获取待审核的选课申请列表
     */
    @GetMapping("/course-applications/pending/{teacherId}")
    public Result<List<Map<String, Object>>> getPendingCourseApplications(
            @PathVariable Long teacherId,
            @RequestParam(required = false) String semester) {
        try {
            System.out.println("📥 Controller收到获取待审核选课申请请求: teacherId=" + teacherId + ", semester=" + semester);
            List<Map<String, Object>> applications = teacherUserService.getPendingCourseApplications(teacherId, semester);
            return Result.success(applications);
        } catch (Exception e) {
            System.err.println("❌ Controller获取待审核选课申请异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取待审核选课申请失败：" + e.getMessage());
        }
    }
    
    /**
     * 审核选课申请
     */
    @PostMapping("/course-applications/review")
    public Result<String> reviewCourseApplication(
            @RequestParam Long studentCourseId,
            @RequestParam Boolean approved,
            @RequestParam(required = false) String rejectReason) {
        try {
            System.out.println("📥 Controller收到审核选课申请请求: studentCourseId=" + studentCourseId + 
                             ", approved=" + approved + ", rejectReason=" + rejectReason);
            boolean success = teacherUserService.reviewCourseApplication(studentCourseId, approved, rejectReason);
            if (success) {
                return Result.success(approved ? "选课申请已通过" : "选课申请已拒绝");
            } else {
                return Result.error("审核失败，请检查申请状态");
            }
        } catch (Exception e) {
            System.err.println("❌ Controller审核选课申请异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("审核选课申请失败：" + e.getMessage());
        }
    }
}


